package io.github.talelin.latticy.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.github.talelin.autoconfigure.exception.NotFoundException;
import io.github.talelin.latticy.common.CommonUtil;
import io.github.talelin.latticy.common.LocalUser;
import io.github.talelin.latticy.dto.JobDTO;
import io.github.talelin.latticy.dto.UpdateCommonJobDTO;
import io.github.talelin.latticy.entity.CommonJob;
import io.github.talelin.latticy.entity.Job;
import io.github.talelin.latticy.entity.Project;
import io.github.talelin.latticy.entity.User;
import io.github.talelin.latticy.model.UserDO;
import io.github.talelin.latticy.repository.JobRepository;
import io.github.talelin.latticy.repository.UserRepository;
import io.github.talelin.latticy.vo.JobByDateVO;
import io.github.talelin.latticy.vo.JobPageVO;
import io.github.talelin.latticy.vo.TeamJobVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class JobService {

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    protected ProjectService projectService;

    @Autowired
    private CommonJobService commonJobService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private SettingService settingService;

    public List<TeamJobVO> getTeamJob() {
        UserDO user = LocalUser.getLocalUser();
        List<User> userList = userRepository.findByIdNot(user.getId());
        if (userList == null) {
            throw new NotFoundException();
        }
        List<TeamJobVO> teamJobVOList = TeamJobVO.getList(userList);
        //迭代器删除元素
        this.iterator(teamJobVOList);
        return teamJobVOList;
    }

    private void iterator(List<TeamJobVO> teamJobVOList) {
        Date date = new Date();
        String now  = CommonUtil.dateToString(date);
        Iterator<TeamJobVO> iterator = teamJobVOList.iterator();
        while (iterator.hasNext()) {
            TeamJobVO teamJobVO = iterator.next();
            Iterator<Job> jobList = teamJobVO.getJobList().iterator();
            while (jobList.hasNext()) {
                Job job = jobList.next();
                Date createTime = job.getCreateTime();
                if (createTime == null) {
                    jobList.remove();
                } else {
                    String time = CommonUtil.dateToString(createTime);
                    if (!now.equals(time)) {
                        jobList.remove();
                    }
                }

            }
            teamJobVO.setCount(teamJobVO.getJobList().size());
        }
    }

    public Integer getUnfinishCount() {
        UserDO user = LocalUser.getLocalUser();
        Date date = new Date();
        String now = CommonUtil.dateToString(date);
        return jobRepository.findUnfinishCount(user.getId(), now);
    }

    public JobPageVO getJobs(int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        UserDO user = LocalUser.getLocalUser();
        List<String> dateList = jobRepository.findCreateTime(user.getId());
        Page<Job> jobList = jobRepository.findByUserIdOrderByCreateTimeDesc(user.getId(), pageable);
        return JobPageVO.builder()
                .dateList(this.listDiff(dateList))
                .jobList(jobList.getContent())
                .total(jobList.getTotalElements())
                .build();
    }

    /**
     * 集合去重
     * @param list
     * @return
     */
    private List listDiff(List<String> list) {
        HashSet set = new HashSet(list);
        list.clear();
        list.addAll(set);
        return list;
    }

    public JobByDateVO getByDate(String time, Long userId) {
        if (userId <= 0) {
            UserDO user = LocalUser.getLocalUser();
            userId = user.getId();
        }
        List<Job> workList = jobRepository.findJobsByDate(1 , userId, time);
        List<Job> studyList = jobRepository.findJobsByDate(2, userId, time);
        return JobByDateVO.builder()
                .workList(workList)
                .studyList(studyList)
                .build();
    }

    public String getLastTime() {
        UserDO user = LocalUser.getLocalUser();
        Timestamp time = jobRepository.findLastCreateTime(user.getId());
        Date now = new Date();
        return time == null ? "" : CommonUtil.dateToString(time);
    }

    public void delete(Long id) {
        Job job = this.get(id);
        Date now = new Date();
        job.setDeleteTime(now);
        jobRepository.save(job);
    }

    public void create(JobDTO dto) {
        Job job = new Job();
        UserDO user = LocalUser.getLocalUser();
        Project project = projectService.get(dto.getProjectId());
        BeanUtils.copyProperties(dto, job);
        job.setUserId(user.getId());
        job.setStatus(false);
        job.setType(project.getType());
        Date time = new Date();
        if (dto.getTime() != null) {
            time = CommonUtil.stringToDate1(dto.getTime());
        }
        job.setCreateTime(time);
        job.setOnline(settingService.getAudit());
        jobRepository.save(job);
    }

    public void update(JobDTO dto, Long id) {
        Job job = this.get(id);
        if (job.getProjectId() != dto.getProjectId()) {
            Project project = projectService.get(dto.getProjectId());
            job.setType(project.getType());
        }
        BeanUtils.copyProperties(dto, job);
        jobRepository.save(job);
    }

    public Job get(Long id) {
        Job job = jobRepository.findFirstById(id);
        if (job == null) {
            throw new NotFoundException();
        }
        return job;
    }

    @Transactional
    public void updateStatus(Long id) {
        Job job = this.get(id);
        //标记为已完成的，今天的可以再次修改
        if (job.getStatus()) {
            if (this.isToday(job.getCreateTime())) {
                job.setStatus(false);
            }
        } else {
            job.setStatus(true);
        }
        jobRepository.save(job);
        //同步公域任务状态
        if (job.getJobId() != null ) {
            commonJobService.updateStatus(job.getJobId(), job.getStatus());
        }

    }

    private boolean isToday(Date time) {
        if (time == null) {
            return false;
        }
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String now  = sdf.format(date);
        String today = sdf.format(time);
        return today.equals(now);
    }

    //同步任务
    public void createJob(CommonJob commonJob, UpdateCommonJobDTO dto) {
        UserDO user = LocalUser.getLocalUser();
        Job job = new Job();
        Date now = new Date();
        job.setProjectId(commonJob.getProjectId());
        job.setType(commonJob.getProject().getType());
        job.setStatus(false);
        job.setTitle(dto.getGetTitle());
        job.setUserId(user.getId());
        job.setJobId(commonJob.getId());
        job.setCreateTime(commonJob.getExpectedTime());
        job.setRemark(commonJob.getRemark());
        jobRepository.save(job);
    }

}
